package com.sgy.nio.selector;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;

/**
 * @author Administrator
 * @date 2025/8/24 17:11
 * @description
 */
public class NIOClient {

    public static void main(String[] args) throws IOException {
        // 打开客户端通道
        SocketChannel socketChannel = SocketChannel.open();

        // 设置连接和端口号
        socketChannel.connect(new InetSocketAddress("127.0.0.1", 9999));

        // 写出数据
        socketChannel.write(ByteBuffer.wrap("hello server".getBytes(StandardCharsets.UTF_8)));

        // 读取服务端写回的数据
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        int read = socketChannel.read(byteBuffer);
        System.out.println("服务端消息：" +  new String(byteBuffer.array(), 0, read, "UTF-8"));

        // 释放资源
        socketChannel.close();
    }
}
